<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.1.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 71.
namespace Rtgm\smecc\SM2;

class Cipher
{
    private $ct = 1;
    private $p2;
    private $sm3keybase;
    private $sm3c3;
    private $key = [];
    private $keyOff = 0;
    private function Reset()
    {
        $this->sm3keybase = new \Rtgm\smecc\SM3\SM3Digest();
        $this->sm3c3 = new \Rtgm\smecc\SM3\SM3Digest();
        $p = [];
        $gmp_x = $this->p2->GetX();
        $x = Hex2ByteBuf::ConvertGmp2ByteArray($gmp_x);
        $this->sm3keybase->BlockUpdate($x, 0, sizeof($x));
        $this->sm3c3->BlockUpdate($x, 0, sizeof($x));
        $gmp_y = $this->p2->GetY();
        $y = Hex2ByteBuf::ConvertGmp2ByteArray($gmp_y);
        $this->sm3keybase->BlockUpdate($y, 0, sizeof($y));
        $this->ct = 1;
        $this->NextKey();
    }
    public function initEncipher($userPoint, $foreignKey = NULL)
    {
        if(empty($foreignKey)) {
            $sm2 = new \Rtgm\sm\RtSm2();
            $foreignKey = $sm2->generatekey();
        }
        list($foreignPriKey, $foreignPubKey) = $foreignKey;
        $this->p2 = $userPoint->mul(gmp_init($foreignPriKey, 16));
        $this->reset();
        return substr($foreignPubKey, -128);
    }
    public function initDecipher($userPoint, $privateKey)
    {
        $this->p2 = $userPoint->mul(gmp_init($privateKey, 16));
        $this->reset();
    }
    private function NextKey()
    {
        $sm3keycur = new \Rtgm\smecc\SM3\SM3Digest();
        $sm3keycur->setSM3Digest($this->sm3keybase);
        $sm3keycur->Update($this->ct >> 24 & 255);
        $sm3keycur->Update($this->ct >> 16 & 255);
        $sm3keycur->Update($this->ct >> 8 & 255);
        $sm3keycur->Update($this->ct & 255);
        $sm3keycur->DoFinal($this->key, 0);
        $this->keyOff = 0;
        $this->ct++;
    }
    public function encryptBlock($data)
    {
        $len = count($data);
        $this->sm3c3->BlockUpdate($data, 0, $len);
        for ($i = 0; $i < $len; $i++) {
            if($this->keyOff == sizeof($this->key)) {
                $this->NextKey();
            }
            $data[$i] ^= $this->key[$this->keyOff++];
        }
        return $data;
    }
    public function decryptBlock($data)
    {
        $len = count($data);
        for ($i = 0; $i < $len; $i++) {
            if($this->keyOff == sizeof($this->key)) {
                $this->NextKey();
            }
            $data[$i] ^= $this->key[$this->keyOff++];
        }
        $this->sm3c3->BlockUpdate($data, 0, $len);
        return $data;
    }
    public function Dofinal()
    {
        $c3 = [];
        $gmp_p = $this->p2->GetY();
        $p = Hex2ByteBuf::ConvertGmp2ByteArray($gmp_p);
        $this->sm3c3->BlockUpdate($p, 0, sizeof($p));
        $this->sm3c3->DoFinal($c3, 0);
        $this->Reset();
        return $c3;
    }
}

?>